CN.record = "条记录";
var msg=CN;
var content = {edit_status:"create",uid:site.uid,attachment:"",canuse:0,fid:"",filepath:""};
$(function(){
	init();
	mpage.modalfactory = function(data,position){//生成列表内容 //TODO 需要变化的地方
        $(".tablist").empty();
        tablist.position = position;//设置数据所在位置
        var tdValue =  "",
            rowclass = "";
            td = function(arg){
            	if(!arg)arg = "-";
            return "<td>"+arg+"</td>";           
            },            
            setnum = function(arg){
            	var color = {current:"",c1:"label-info",c2:"label-success"};
            	switch(arg){
	            	case "1":color.current = color.c1;break;
	            	case "2":color.current = color.c2;break;
            	}
            	return "<span class='label "+color.current+"'>"+arg+"<span>";
            },
            setButton = function(data){
            	var btns = '<div class="btn-group" data-toggle="buttons-radio">';
            	btns += "<a class='btn btn-info btn-mini' onclick='del(this)' data-name='"+data.title+"' data-id='"+data.ecid+"'>移除</a>";
            	btns += "</div>";
            	return btns;
            },
            settitle = function(data){
            	return '<button class="btn btn-info btn-mini" onclick="get(this)" type="button"  data-id="'+data.ecid+'">'+data.title+'</button>';
            },
            setectype = function(type){
            	var key =["","活动简介","活动会场","活动交通","活动资料","活动实录","活动新闻","活动文章","关于我们","参加回执","活动APP背景","活动APP主题曲"];
            	return "<span class='label label-info'>"+key[type]+"</span>";
            },
            setstatus = function(arg){
            	var key = ["暂停","正常"];
            	return "<span class='label label-info'>"+key[arg]+"</span>";
            },
            seturl = function(arg){
            	return "<a href='"+arg+"' target='_blank'>链接</a>";
            };
        for ( var element in data) {
        	var kk =data[element],
             	tdValue =td(setnum(kk.num))+ 
            	td(settitle(kk))+
            	td(kk.content)+ 
            	td(seturl(kk.url))+
            	td(setectype(kk.ectype))+ 
            	td(setstatus(kk.status))+
             	td(setButton(kk));
               	rowclass = element%2;//行样式
               $(".tablist").append("<tr class='tr"+rowclass+"'>"+tdValue+"</tr>");
        }
    };
    mpage.setext("?eid="+getUrlParam("eid"));
	mpage.init();
}); 


function init(){
	swfupload_configure();//need to be static by vincent20130808
	init_dialog();
	init_upload_configure();
	//initToolbarBootstrapBindings();  
	//$('#editor').wysiwyg();
	//window.prettyPrint && prettyPrint();	  

}

init_upload_configure = function(){	
	$(".uploadbtn").click(function(){
		$('#myModal').modal('hide');
		$('#uploadModal').modal('show');		
	});
	
}

function initToolbarBootstrapBindings() {//wysiwyg
    var fonts = ['Serif', 'Sans', 'Arial', 'Arial Black', 'Courier', 
          'Courier New', 'Comic Sans MS', 'Helvetica', 'Impact', 'Lucida Grande', 'Lucida Sans', 'Tahoma', 'Times',
          'Times New Roman', 'Verdana'],
          fontTarget = $('[title=Font]').siblings('.dropdown-menu');
    $.each(fonts, function (idx, fontName) {
        fontTarget.append($('<li><a data-edit="fontName ' + fontName +'" style="font-family:\''+ fontName +'\'">'+fontName + '</a></li>'));
    });
    $('a[title]').tooltip({container:'body'});
  	$('.dropdown-menu input').click(function() {return false;})
		    .change(function () {$(this).parent('.dropdown-menu').siblings('.dropdown-toggle').dropdown('toggle');})
      .keydown('esc', function () {this.value='';$(this).change();});

    $('[data-role=magic-overlay]').each(function () { 
      var overlay = $(this), target = $(overlay.data('target')); 
      overlay.css('opacity', 0).css('position', 'absolute').offset(target.offset()).width(target.outerWidth()).height(target.outerHeight());
    });
    /*if ("onwebkitspeechchange"  in document.createElement("input")) {
      var editorOffset = $('#editor').offset();
      $('#voiceBtn').css('position','absolute').offset({top: editorOffset.top, left: editorOffset.left+$('#editor').innerWidth()-35});
    } else {
      $('#voiceBtn').hide();
    }*/
};

function showErrorAlert (reason, detail) {//wysiwyg
	var msg='';
	if (reason==='unsupported-file-type') { msg = "Unsupported format " +detail; }
	else {
		console.log("error uploading file", reason, detail);
	}
	$('<div class="alert"> <button type="button" class="close" data-dismiss="alert">&times;</button>'+ 
	 '<strong>File upload error</strong> '+msg+' </div>').prependTo('#alerts');
};


init_dialog = function(){
	$("#dialog_create").click(function(){//create & open dialog
		content.edit_status = "create";
		open_dialog();
	});
	$("#dialog_save").click(function(){
		$(this).attr("disabled",true);
		$(".dialogmsg").text("执行操作中...");
		$("#form1 input").each(function(){
			var id = $(this).attr("id");
			if(id)
				content[id] =  $(this).val();
		});	
		if(!content.title||!content.ectype){
			$(".dialogmsg").text("标题信息和活动内容形式必须填写和选择!");
			return;
		}
		
		content.content = $("#content").val();
		content.uid = site.uid;
		content.requesturl = site.web+"my/"+site.title+"/"+content.edit_status;//包含create/update操作
		content.eid = getUrlParam("eid");
		//content.content = $('#editor').html();//20130812 change to wysiwyg vincent
		complete = function(data){
			done_method = function(){
				$('#myModal').modal('hide');
				mpage.init();
			};
			if(data.code==1){
				$(".dialogmsg").text("操作成功!");
				setTimeout(done_method, 2000);
				
			}else{
				$('#myModal').modal('hide');
			}
			
		}
		GG(content,complete);
	});
	$(".canceldialog").click(function(){//cancel
		clear_dialog();
		$('#myModal').modal('hide');
	});
	$(".canceldialog2").click(function(){//cancel uploadfile dialog
		get_uploadfileinfo();
		$('#uploadModal').modal('hide');
		$('#myModal').modal('show');
	});
	
	$(".useflag").click(function(){//click canuse type
		content.canuse = $(this).attr("key");
	});
	
}

clear_dialog = function(){
	$("#form1 input[type=reset]").click();
	$("#dialog_save").attr("disabled",false);
	$(".contentlist").empty();
	$(".fname").text("");
	$(".typetooltips").text("");
	$(".dialogmsg").text("");
}

get_uploadfileinfo = function(){
	$(".fname").text();
	if(ufile.fid!=""){//有上传文件
		content.attachment = ufile.name;
		content.fid = ufile.fid;
		content.filepath = ufile.filepath;
		$(".fname").text(ufile.name);
	}
}

open_dialog = function(data){
	clear_dialog();
	switch(content.edit_status){
		case "create":
			$(".dialog_status").text("新增");
			getectype("add");
			content.attachment = "";
			content.fid = "";
			content.canuse = "";
			content.filepath = "";
			break;
		case "update":
			$(".dialog_status").text("更新");
			$.each(data, function(index, value) {
				$("#"+index).val(value);
			});
			if(data.canuse!=""){//set attachment status
				if(data.canuse==0){
					$("#cannotuse").click();
				}else{
					$("#canuse").click();					
				}
			}
			content.attachment = data.attachment;
			content.fid = data.fid;
			content.canuse = data.canuse;
			content.filepath = data.filepath;
			content.ectype = data.ectype;
			$(".fname").text(data.attachment);
			
			//$('#editor').html(data.content);//wysiwyg 20130812 vincent
			getectype("edit",data.ectype);
			break;
	}
	$('#myModal').modal('show');
}

get = function(arg){
	var id = $(arg).attr("data-id");
	cb = function (data){
		if(data.code==1){
			content.edit_status = "update";
			open_dialog (data.data);
		}else{
			alert("ERROR content 404");
		}
	}
	var url = site.web+"my/"+site.title+"/get";
	var json = {url:url,ecid:id,uid:site.uid};
	G(json,cb);
}

del = function(arg){
	var name =  $(arg).attr("data-name");
	if(confirm("确认移除"+name+"?")==false)return;
	var id = $(arg).attr("data-id");
	cb = function (data){
		mpage.init();
	}
	var url = site.web+"my/"+site.title+"/del";
	var json = {url:url,ecid:id,uid:site.uid};
	G(json,cb);
}

getectype = function(status,selectid){//venue
	cb = function (data){
		if(data.code==1){
			var list = "<select id='contentselect'>";
			if(status=="add")
				list += "<option value='0'>请选择..</option>";
			for(var key in data.data){
				var id = data.data[key]['num'],
					name = data.data[key]['name'];
				if(selectid==id){
					list += "<option value='"+id+"' selected='selected'>"+name+"</option>";
				}else{
					list += "<option value='"+id+"' >"+name+"</option>";
				}
			}
			list+="<select>";
			$(".contentlist").append(list);			
			$('#contentselect').change(function(){ //设置 ectype
				content.ectype = $(this).children('option:selected').val();
				$(".typetooltips").text("");
				switch(content.ectype){
					case "11":$(".typetooltips").text("请上传活动的主题曲(MP3,WAV)");break;
					case "10":$(".typetooltips").text("请上传APP活动的图片背景");break;
					case "9":$(".typetooltips").text("请上传APP活动的参加回执,如入场卷或活动图片");break;
				}
			});			
		}else{
			$(".contentlist").append("<span class='label'>没有内容信息,请通知管理员</span>");
		}
	}
	
	var url = site.web+"my/"+site.title+"/getectype";
	var json = {url:url,uid:site.uid};
	G(json,cb);
}

swfupload_configure = function(){
	//属性赋值[1]
	var furl 	= site.web + "js/swfupload/swfupload.swf",
		uurl 	= site.web + "my/service/upload",
		btnurl 	= site.web + "skin/img/swfupload.png",
		ssid 	= site.ssid,
		uid 	= site.uid;
	//setting设置[2]
	var settings = {
		flash_url :furl ,
		upload_url: uurl,
		post_params: {"PHPSESSID" : ssid,"uid":uid},
		file_size_limit : "1000 MB",
		file_types : "*.*",
		file_types_description : "All Files",
		file_upload_limit : 10,  
		file_queue_limit : 0,
		custom_settings : {
			progressTarget : "fsUploadProgress",
			cancelButtonId : "btnCancel"
		},
		debug:false,

		// Button settings
		button_image_url: btnurl,
		button_width: "60",
		button_height: "25",
		button_placeholder_id: "spanButtonPlaceHolder",
		button_text: '<span class="theFont">浏览</span>',
		button_text_style: ".theFont { font-size: 14px; color:#ffffff; cursor:pointer;}",
		button_text_left_padding: 14,
		button_text_top_padding: 2,
		
		file_queued_handler : fileQueued,
		file_queue_error_handler : fileQueueError,
		file_dialog_complete_handler : fileDialogComplete,
		upload_start_handler : uploadStart,
		upload_progress_handler : uploadProgress,
		upload_error_handler : uploadError,
		upload_success_handler : uploadSuccess,
		upload_complete_handler : uploadComplete,
		queue_complete_handler : queueComplete	
	};
	//new SWFupload[3]
	swfu = new SWFUpload(settings);
}